package com.hghivln.blog.shiro;

import com.hghivln.blog.common.exception.BlogException;
import com.hghivln.blog.common.lang.ResultEnum;
import com.hghivln.blog.common.lang.UserTypeEnum;
import com.hghivln.blog.entity.SysUser;
import com.hghivln.blog.entity.User;
import com.hghivln.blog.service.SysUserService;
import com.hghivln.blog.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        LoginToken token = (LoginToken) authenticationToken;
        String username = token.getUsername();
        System.out.println(token.getUserType());
        if (token.getUserType().equals(UserTypeEnum.SYS_USER)){
            SysUser sysUser = sysUserService.getByUsername(username);
            if (StringUtils.isEmpty(sysUser)) {
                throw new BlogException(ResultEnum.LOGIN_PARAM_ERROR);
            }
            // 转json 或拷贝属性
            LoginUser loginUser = new LoginUser();
            BeanUtils.copyProperties(sysUser,loginUser);
            return new SimpleAuthenticationInfo(loginUser,loginUser.getPassword(),this.getName());
        } else {
            User user = userService.getByUsername(username);
            if (StringUtils.isEmpty(user)) {
                throw new BlogException(ResultEnum.LOGIN_PARAM_ERROR);
            }
            // 转json 或拷贝属性
            LoginUser loginUser = new LoginUser();
            BeanUtils.copyProperties(user,loginUser);
            loginUser.setId(user.getUserId());
            return new SimpleAuthenticationInfo(loginUser,loginUser.getPassword(),this.getName());
        }

    }

}
